#include "db.h"
#include "3rdparty/sqllite/sqlite3.h"

Database::Database(const char* filename)
{
    database = NULL;
    if(sqlite3_open(filename, &database) != SQLITE_OK)
    {
        throw std::logic_error(sqlite3_errmsg(database));
    }
}

Database::~Database()
{
    if (sqlite3_close(database) != SQLITE_OK)
    {
        throw std::logic_error(sqlite3_errmsg(database));
    }
}

 std::vector<std::vector<std::string> >  Database::Query(const char* query)
{
    sqlite3_stmt *statement;
    std::vector<std::vector<std::string> >  results;

    if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK)
    {
        int cols = sqlite3_column_count(statement);
        int result = 0;
        while(true)
        {
            result = sqlite3_step(statement);

            if(result == SQLITE_ROW)
            {
                std::vector<std::string> values;
                for(int col = 0; col < cols; col++)
                {
                    values.push_back((char*)sqlite3_column_text(statement, col));
                }
                results.push_back(values);
            }
            else
            {
                break;
            }
        }
        sqlite3_finalize(statement);
    }
    else
    {
        throw std::logic_error(sqlite3_errmsg(database));
    }

    return results;
}

